package com.javaspeak.designpatterns.go4.behavioural.iterator;

import org.apache.log4j.BasicConfigurator;
import org.junit.Test;
import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;

/**
 * Tests add, remove and the usage of an iterator for the ConcurrentLinkedList
 * in a single threaded environment.
 *
 * @author John Dickerson
 */
public class ConcurrentLinkedListSingleThreadedTest {

    @Test
    public void testIterator(){

        // the values to add
        String[] valuesToAdd =
            { "Hello", "World!", "How", "bling", "blah", "is", "it", "doing?" };

        ConcurrentLinkedList<String> linkedList = new ConcurrentLinkedList<String>();

        for ( String value : valuesToAdd ){

            // add the values to the list
            linkedList.add( value );
        }

        // remove some values from the list
        linkedList.remove( "bling" );
        linkedList.remove( "blah" );

        // Create a snapshot iterator
        SnapshotIterator<String> snapshotIterator =
            linkedList.getSnapshotIterator();

        // Add some further values to the list. These should not be present
        // in the iterator as it is snapshot iterator and has been created
        // already.
        linkedList.add( "Wow" );

        // Remove some further values from the list. These should not be
        // removed from the iterator as it is a snapshot iterator and has been
        // created already.
        linkedList.remove( "Hello" );

        int i=0;
        String actualValue;

        // the expected values to be returned by the iterator (note that bling
        // and blah) have been removed from the list
        String[] expectedValues =
            { "Hello", "World!", "How", "is", "it", "doing?" };

        while ( snapshotIterator.hasNext() ){

            actualValue = snapshotIterator.next();
            System.out.println( actualValue );

            org.junit.Assert.assertEquals( expectedValues[ i ], actualValue );
            i++;
        }
    }


    public static void main( String args[] ){

        BasicConfigurator.resetConfiguration();
        BasicConfigurator.configure();

        JUnitCore junitCore = new JUnitCore();
        junitCore.addListener( new TextListener( System.out ) );
        junitCore.run( ConcurrentLinkedListSingleThreadedTest.class );
    }
}
